package com.xinchili.autoddl.autoClass.util;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;

import java.lang.Class;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.*;

public class ReflectionUtils {

    public static List<Field> getAllFields(Class<?> clazz) {
        List<Field> fields = new ArrayList<>();
        while (clazz != Object.class && clazz != null) {
            Collections.addAll(fields, clazz.getDeclaredFields());
            clazz = clazz.getSuperclass();
        }
        return fields;
    }

    public static Set<Class<?>> scanClassesWithAnnotation(List<String> packages, Class<?> annotationClass) {
        Set<Class<?>> classes = new HashSet<>();
        ClassPathScanningCandidateComponentProvider scanner =
                new ClassPathScanningCandidateComponentProvider(true);
        scanner.addIncludeFilter(new AnnotationTypeFilter((Class<? extends Annotation>) annotationClass));

        for (String pkg : packages) {
            for (BeanDefinition bd : scanner.findCandidateComponents(pkg)) {
                try {
                    classes.add(Class.forName(bd.getBeanClassName()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return classes;
    }
}
